import { defineStore } from "pinia";
import router from "../router";
import instance from "@/utils/axios";

export const useAuthStore = defineStore("auth", {
  state: () => ({
    opType: "1", // 1=员工登录，0=管理员登录
    userName: "",
    userPassword: "",
    errorMsg: "",
     currentLoginId: null, // 新增：存储当前登录用户的loginId
  }),
  actions: {
    // 切换登录类型（已存在）
    selectLogin(type) {
      this.opType = type;
      this.clearForm(); // 切换时清空表单
    },

    // 清空表单（新增：复用性高）
    clearForm() {
      this.userName = "";
      this.userPassword = "";

      this.errorMsg = "";
    },

    // 登录逻辑（已存在，保持不变）
    async login() {
      if (!this.userName || !this.userPassword) {
        this.errorMsg = "请输入用户名和密码";
        return;
      }

      try {
        let res;
        if (this.opType === "0") {
          res = await this.adminLogin();
        } else {
          res = await this.employeeLogin();
        }

        if (res.data.code === 200) {
          localStorage.setItem("token", res.data.token);

          this.clearForm();
          // 根据用户类型跳转页面
          if (this.opType === "0") {
            router.push("/userManager/home");
          } else {
            router.push("/emp/home");
          }
        } else {
          this.errorMsg = res.data.message || "用户名或密码错误";
        }
      } catch (e) {
        console.error("登录失败：", e);
        // 根据错误类型设置不同的错误消息
        if (e.response && e.response.data) {
          this.errorMsg = e.response.data.message || "登录失败";
        } else {
          this.errorMsg = "网络连接失败，请检查网络设置";
        }
      }
    },
    // 管理员登录
    async adminLogin() {
      const username = this.userName.trim();
      const password = this.userPassword;

      const res = await instance.post("/admin/login", {
        adminUsername: username,
        adminPassword: password,
      });

      return res;
    },

    // 员工登录
    async employeeLogin() {
      const username = this.userName.trim();
      const password = this.userPassword;

      const res = await instance.post("/user/login", {
        empUsername: username,
        empPassword: password,
      });
      // 从响应数据中提取loginId
  if (res.data.code === 200) {
    const loginId = res.data.data.loginId;
    
    // 将loginId存储到状态管理中
    this.currentLoginId = loginId;
    
    // 可以将loginId存储到localStorage中
    localStorage.setItem('currentLoginId', loginId);
  }
  
  return res;
},

    // 新增：员工注册方法
    async register() {
      // 1. 前端表单校验（保持不变）
      const username = this.userName.trim();
      const password = this.userPassword;

      if (!username) {
        this.errorMsg = "用户名不能为空";
        return;
      }
      if (username.length < 3 || username.length > 12) {
        this.errorMsg = "用户名长度需在 3-12 位之间";
        return;
      }
      if (!password) {
        this.errorMsg = "密码不能为空";
        return;
      }
      if (password.length < 6) {
        this.errorMsg = "密码长度不能少于6位";
        return;
      }

      try {
        // 2. 调用注册接口，参数名适配后端的 empUsername 和 empPassword
        const res = await instance.post("/user/register", {
          empUsername: username, // 关键：参数名改为 empUsername
          empPassword: password, // 关键：参数名改为 empPassword
          // 若后端需要类型参数则保留
        });

        // 3. 注册成功处理
        this.errorMsg = "注册成功，请登录";
        this.userName = "";
        this.userPassword = "";
      } catch (e) {
        // 4. 注册失败处理
        console.error("注册失败：", e);
        this.errorMsg = e.response?.data?.message || "注册失败，请重试";
      }
    },
  },
});
